package com.jiangnan.ui.activity

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.jiangnan.R
import com.jiangnan.databinding.ActivityNavigationBinding
import com.jiangnan.ui.fragment.MyFragment
import com.jiangnan.ui.fragment.RecommendFragment
import com.jiangnan.ui.fragment.RespositoryFragment
import com.jiangnan.ui.fragment.ReturnFragment

/**
 * Fragment+TabLayout实现底部导航栏
 */
class NavigationActivity : AppCompatActivity() {
    private val TAG = "NavigationActivity"

    private val titles = arrayOf(
        "库存",
        "推荐",
        "还书",
        "我的"
    )
    private val icons = intArrayOf(
        R.drawable.book_respositort_selector,
        R.drawable.book_recommend_selector,
        R.drawable.book_return_selector,
        R.drawable.book_me_selector
    )

    private var titleTxt: TextView? = null

    /**
     * 当前正在显示的Fragment
     */
    private var currentFragment: Fragment? = null

    private val fragments = arrayOfNulls<Fragment>(4)

    private var position = 0

    private var tabLayout: TabLayout? = null

    private lateinit var binding: ActivityNavigationBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i(TAG, "onCreate:$savedInstanceState")
        // 使用 DataBinding 初始化布局
        binding = DataBindingUtil.setContentView(this, R.layout.activity_navigation)
        binding.lifecycleOwner = this

        initView()
        initFagment(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt("postion", position)
        super.onSaveInstanceState(outState)
    }

    /**
     * 初始化Fragment
     */
    private fun initFagment(savedInstanceState: Bundle?) {
        val manager = supportFragmentManager
        if (savedInstanceState != null) {
            fragments[0] = manager.findFragmentByTag("0") as RespositoryFragment?
            fragments[1] = manager.findFragmentByTag("1") as RecommendFragment?
            fragments[2] = manager.findFragmentByTag("2") as ReturnFragment?
            fragments[3] = manager.findFragmentByTag("3") as MyFragment?

            position = savedInstanceState.getInt("postion")

            val b = manager.beginTransaction()
            for (i in 0..3) {
                if (fragments[i] == null) {
                    continue
                }
                if (i == position) {
                    b.show(fragments[i]!!)
                    currentFragment = fragments[i]
                } else {
                    b.hide(fragments[i]!!)
                }
            }
            b.commit()
        }
        if (fragments[0] == null) {
            fragments[0] = RespositoryFragment()
        }
        if (fragments[1] == null) {
            fragments[1] = RecommendFragment()
        }
        if (fragments[2] == null) {
            fragments[2] = ReturnFragment()
        }
        if (fragments[3] == null) {
            fragments[3] = MyFragment()
        }

        if (savedInstanceState == null) {
            //默认显示首页
            replacePage(position)
        }

        tabLayout!!.getTabAt(position)!!.select()
    }


    /**
     * 初始化view
     */
    private fun initView() {
        titleTxt = binding.acNavigationTitle

        tabLayout = binding.acNavigationTab

        for (i in 0..3) {
            val v: View = LayoutInflater.from(this).inflate(R.layout.custom_tab_item, null)
            val img = v.findViewById<ImageView>(R.id.tv_img)
            val tv = v.findViewById<TextView>(R.id.tab_tv)
            tv.text = titles[i]
            img.setBackgroundResource(icons[i])
            tabLayout?.newTab()?.let { tabLayout?.addTab(it.setCustomView(v)) }
        }

        tabLayout?.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                Log.i(TAG, "onTabSelected:" + titles[tab.position])
                replacePage(tab.position)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                Log.i(TAG, "onTabUnselected:" + titles[tab.position])
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                Log.i(TAG, "onTabReselected:" + titles[tab.position])
            }
        })
    }


    /**
     * 切换fragment显示
     * @param index 需要显示的fragment 序号
     */
    private fun replacePage(index: Int) {
        if (index < 0 || index > 3) {
            return
        }
        titleTxt!!.text = titles[index]
        val fragment = fragments[index]
        if (null == fragment || fragment === currentFragment) {
            return
        }
        val transaction = supportFragmentManager
            .beginTransaction()
        if (!fragment.isAdded) {
            transaction.add(R.id.ac_navigation_container, fragment, "" + index)
        }
        val oldFragment = currentFragment
        if (null != oldFragment) {
            transaction.hide(oldFragment).show(fragment).commit()
        } else {
            transaction.show(fragment).commit()
        }
        currentFragment = fragment
        position = index
    }
}